package com.fx.ruankao.controller;

import com.fx.ruankao.entity.UserAnswer;
import com.fx.ruankao.service.UserAnswerService;
import com.fx.ruankao.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 用户答案控制器 - 管理端
 */
@RestController
@RequestMapping("/api/admin/answers")
public class UserAnswerController {
    
    @Autowired
    private UserAnswerService userAnswerService;
    
    /**
     * 新增用户答案
     */
    @PostMapping
    public Result insert(@RequestBody UserAnswer userAnswer) {
        try {
            int result = userAnswerService.insert(userAnswer);
            if (result > 0) {
                return Result.success("新增答案成功");
            } else {
                return Result.error("新增答案失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID删除用户答案
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        try {
            int result = userAnswerService.deleteById(id);
            if (result > 0) {
                return Result.success("删除答案成功");
            } else {
                return Result.error("删除答案失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户答案
     */
    @PutMapping
    public Result update(@RequestBody UserAnswer userAnswer) {
        try {
            int result = userAnswerService.update(userAnswer);
            if (result > 0) {
                return Result.success("更新答案成功");
            } else {
                return Result.error("更新答案失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询用户答案
     */
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id) {
        try {
            UserAnswer userAnswer = userAnswerService.selectById(id);
            if (userAnswer != null) {
                return Result.success(userAnswer);
            } else {
                return Result.error("未找到答案");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据考试记录ID查询用户答案列表
     */
    @GetMapping("/record/{recordId}")
    public Result selectByRecordId(@PathVariable Integer recordId) {
        try {
            List<UserAnswer> userAnswers = userAnswerService.selectByRecordId(recordId);
            return Result.success(userAnswers);
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 批量插入用户答案
     */
    @PostMapping("/batch")
    public Result batchInsert(@RequestBody List<UserAnswer> userAnswers) {
        try {
            int result = userAnswerService.batchInsert(userAnswers);
            if (result > 0) {
                return Result.success("批量保存答案成功");
            } else {
                return Result.error("批量保存答案失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 删除考试记录下的所有答案
     */
    @DeleteMapping("/record/{recordId}")
    public Result deleteByRecordId(@PathVariable Integer recordId) {
        try {
            int result = userAnswerService.deleteByRecordId(recordId);
            if (result > 0) {
                return Result.success("删除考试记录下的所有答案成功");
            } else {
                return Result.error("删除考试记录下的所有答案失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 计算考试成绩
     */
    @GetMapping("/calculate-score/{recordId}")
    public Result calculateScore(@PathVariable Integer recordId) {
        try {
            Integer score = userAnswerService.calculateScore(recordId);
            if (score != null) {
                return Result.success(score, "计算成绩成功");
            } else {
                return Result.error("计算成绩失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 提交单个题目答案
     */
    @PostMapping("/submit")
    public Result submitAnswer(@RequestBody UserAnswer userAnswer) {
        try {
            // 检查是否已存在该题目的答案
            List<UserAnswer> existingAnswers = userAnswerService.selectByRecordId(
                userAnswer.getRecordId() != null ? userAnswer.getRecordId().intValue() : null
            );
            UserAnswer existingAnswer = null;
            if (existingAnswers != null) {
                for (UserAnswer answer : existingAnswers) {
                    if (answer.getQuestionId() != null && answer.getQuestionId().equals(userAnswer.getQuestionId())) {
                        existingAnswer = answer;
                        break;
                    }
                }
            }
            
            if (existingAnswer != null) {
                // 更新现有答案
                existingAnswer.setUserAnswer(userAnswer.getUserAnswer());
                existingAnswer.setIsCorrect(userAnswer.getIsCorrect());
                userAnswerService.update(existingAnswer);
            } else {
                // 新增答案
                userAnswerService.insert(userAnswer);
            }
            
            return Result.success("提交答案成功");
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据用户ID和试卷ID查询答案
     */
    @GetMapping("/user/{userId}/paper/{paperId}")
    public Result selectByUserIdAndPaperId(@PathVariable Integer userId, @PathVariable Integer paperId) {
        try {
            List<UserAnswer> userAnswers = userAnswerService.selectByUserIdAndPaperId(userId, paperId);
            return Result.success(userAnswers);
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 查询答案统计数量
     */
    @GetMapping("/count")
    public Result count() {
        try {
            int count = userAnswerService.countAnswers();
            return Result.success(count);
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    

}